
const app = getApp()
import prizeApi from '../../api/prizeApi'
import msgCheck from '../../util/msgCheck'

import uploadImgList from '../../util/uploadImgList'
import formatDateTime from '../../util/formatDateTime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prizeId: '',
    content: '',
    imgList: [],
    fileList: [],
    date:'',
 
    deleteFiles: [],

    
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.data.prizeId = options.prizeId
   
  },

  previewImage(e){
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgList,
      current: url
    })
  },

  contentInput: function(e) {
    var val = e.detail.value;

    this.setData({
      content: val
    });
  },
  chooseImage:function(){
    wx.chooseMedia({
      count: 9 - this.data.imgList.length,
      mediaType: ['image'],
      success: (res) => {
        let list = res.tempFiles.map(obj => obj.tempFilePath)
        const tempFilePaths = this.data.imgList.concat(list)
        this.setData({
          imgList: tempFilePaths
        })
      }
    })
  },

  delImg(e){
  
    var index = e.currentTarget.dataset.index
    this.data.imgList.splice(index,1)
    var fileIds = this.data.fileList.splice(index,1)
    if(fileIds[0]){
      this.data.deleteFiles.push(fileIds[0])
    }
    this.setData({
      imgList: this.data.imgList
    })
  },


  async submit(){
    let pass = await msgCheck(this.data.content)
   if(!pass){
      return
   }
     

    if(this.data.imgList.length == 0 && (!this.data.content)){
      wx.showToast({
        title:'没有可提交的内容',
        icon:'none'
      })
      return 
    }


    wx.showLoading({
      mask:true
    })
    var res = await uploadImgList(this.data.imgList, this.data.fileList)
    
    
    var params = {
      prizeId: this.data.prizeId,
      fileID: res[0].fileID,
      avatarUrl: res[0].tempFileURL,
      nickName:this.data.content,
      openid: Math.random() + 'sdfd'
    }

    await prizeApi.openPrize(params)
    await prizeApi.updatePrize({
      id: this.data.prizeId,
      status: 1
    })

    // params.type = 'prize'
    // mediaCheck(params)

    await wx.cloud.callFunction({
      name: 'sendMsg',
      data: {
          type: 'openPrizeSend',
          prizeId: this.data.prizeId,
      }
  })

    wx.hideLoading()
    wx.navigateBack()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})